package main

import (
	"fmt"
	"math/rand"
	"time"
)

// Work
func Work(id int, c chan int) {
	for n := range c {
		fmt.Printf("Worker %d received number %d\n", id, n)
	}
}

// NewWorkerWithChannel
func NewWorkerWithChannel(id int) chan<- int {
	c := make(chan int)
	go Work(id, c)
	return c
}

func generator() chan int {
	out := make(chan int)
	go func() {
		i := 0
		for {
			time.Sleep(time.Millisecond * time.Duration(rand.Intn(1500)))
			out <- i
			i++
		}
	}()
	return out
}

func main() {
	var c1, c2 = generator(), generator()
	var r = NewWorkerWithChannel(1) //没有make，此时的c1和c2为nil
	//使用队列是为了防止数据积压时有的数据被冲掉而来不及输出
	var q_id []int
	var q_value []int
	tick := time.Tick(time.Duration(2.5 * float64(time.Second)))
	end := time.After(10 * time.Second)
	for {
		var active_rec_chan chan<- int
		var act_value int
		if len(q_id) > 0 {
			active_rec_chan = r
			act_value = q_id[0]*100 + q_value[0]
		}
		select {
		case n := <-c1:
			q_id = append(q_id, 1)
			q_value = append(q_value, n)
		case n := <-c2:
			q_id = append(q_id, 2)
			q_value = append(q_value, n)
			//使用case语句传value可以避免在case输入语句中阻塞
		case active_rec_chan <- act_value:
			q_value = q_value[1:]
			q_id = q_id[1:]
		case <-tick:
			fmt.Println("我是tick桑")
		case <-end:
			fmt.Println("The program has been shutdown")
			return
		case <-time.After(800 * time.Millisecond):
			fmt.Println("Time out")
			//default://如果有default那就不会阻塞，vice versa
			//fmt.Println("nothing happened")
		}
	}
}
